package com.heima.tlias.aspect;

import com.heima.tlias.dao.OperateLogMapper;
import com.heima.tlias.pojo.OperateLog;
import com.heima.tlias.utils.UserThreadLocalUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
@RequiredArgsConstructor
@Slf4j
public class LogAspect {

    private final HttpServletRequest request;

    private final OperateLogMapper operateLogMapper;

    @Around("@annotation(com.heima.tlias.anno.Log)")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        String threadName = Thread.currentThread().getName();
        log.info("LogAspect 当前线程名称:{}",threadName);
        //1. 获取到需要记录的信息
        //1.1 获取操作人信息
        Integer userId = UserThreadLocalUtil.get();
        //1.2 获取操作时间
        LocalDateTime time = LocalDateTime.now();
        //1.3 获取目标类的类名
        String className = joinPoint.getTarget().getClass().getName();
        //1.4 获取目标方法的方法名称
        String methodName = joinPoint.getSignature().getName();
        //1.5 获取调用目标方法传入的参数
        Object[] args = joinPoint.getArgs();
        //记录执行的开始时间
        long begin = System.currentTimeMillis();
        //1.6 获取目标方法执行的返回结果
        Object returnValue = joinPoint.proceed();
        //1.7 获取目标方法的执行时间
        long end = System.currentTimeMillis();
        long costTime = end - begin;
        //2. 调用数据访问层保存到数据库
        OperateLog operateLog = new OperateLog(null,userId,time,className,methodName, Arrays.toString(args),returnValue==null?"":returnValue.toString(),costTime);
        operateLogMapper.insert(operateLog);

        return returnValue;
    }
}
